package com.zxn.xm.text;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Color;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.util.Pair;
import android.view.animation.LinearInterpolator;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zxn on 2019/6/1.
 */
public class FadeInTextView extends AppCompatTextView {

    private final StringBuffer stringBuffer = new StringBuffer();
    private String[] arr;
    private int textCount;
    private int currentIndex = -1;
    /**
     * 每个字出现的时间
     */
    private static final long DURATION_DEFAULT = 300L;
    private ValueAnimator textAnimation;
    private TextAnimationListener textAnimationListener;
    private final String TAG = FadeInTextView.class.getSimpleName();

    public FadeInTextView(Context context) {
        this(context, null);
    }

    public FadeInTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        /*TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.Fad);
        duration = ta.getInteger(R.styleable.FadeInTextView_, 0);
        ta.recycle();*/
    }

    /**
     * 文字逐个显示动画  通过插值的方式改变数据源
     */
    private void initAnimation() {
        //从0到textCount - 1  是设置从第一个字到最后一个字的变化因子
        textAnimation = ValueAnimator.ofInt(0, textCount - 1);
        //textAnimation = ValueAnimator.ofInt(0, textCount);
        //执行总时间就是每个字的时间乘以字数
        textAnimation.setDuration(textCount * DURATION_DEFAULT);
        //匀速显示文字
        textAnimation.setInterpolator(new LinearInterpolator());
        textAnimation.addUpdateListener(valueAnimator -> {
            int index = (int) valueAnimator.getAnimatedValue();
            Log.e(TAG, "initAnimation: " + index);
            //过滤去重，保证每个字只重绘一次
            if (currentIndex != index) {
                stringBuffer.append(arr[index]);
                currentIndex = index;
                //所有文字都显示完成之后进度回调结束动画
                if (currentIndex == (textCount - 1)) {
                    if (textAnimationListener != null) {
                        textAnimationListener.animationFinish();
                    }
                }

                onUpdateText(stringBuffer);
                //新思路的做法
                //setText(stringBuffer.toString());
            }
        });


    }

    //StringBuffer
    private void onUpdateText(StringBuffer stringBuffer) {
        if (mPartTextList.isEmpty() || currentIndex < mPartTextList.get(0).getStart()) {
            setText(stringBuffer);
        } else {
            SpannableString styledText = new SpannableString(stringBuffer);
            for (int i = 0; i < mPartTextList.size(); i++) {
                int color = mPartTextList.get(i).getColor();
                int startIndex = mPartTextList.get(i).getStart();
                if (currentIndex < startIndex) {
                    break;
                }
                //startIndex = Math.min(currentIndex, startIndex);
                int end = mPartTextList.get(i).getEnd();
                Log.e(TAG, "onUpdateText: end--" + end);
                //end--64
                //end = Math.min(currentIndex, end);
                if (end > currentIndex) {
                    end = currentIndex + 1;
                }
                Log.e(TAG, "onUpdateText: " + end);
                //onUpdateText: 62,
                styledText.setSpan(new ForegroundColorSpan(color),
                        startIndex,
                        end,
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            setText(styledText, BufferType.SPANNABLE);
        }
    }

    /**
     * 设置文本内容其中文字的颜色
     *
     * @param color      颜色
     * @param startIndex 开始位置
     */
    public FadeInTextView setPartTextColor(int color, int startIndex, int endIndex) {
        if (arr == null || arr.length == 0) {
            throw new NullPointerException("Please Set The textView Content!");
        }
        //SpannableString styledText = new SpannableString(getText());
        //styledText.setSpan(new ForegroundColorSpan(color), startIndex, startIndex + text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        //setText(styledText, BufferType.SPANNABLE);
//        for (int i = startIndex; i < (startIndex + text.length()); i++) {
//            //Pair<Integer, Integer> textPair = new Pair<>(startIndex, color);
//            //partTextPairList.add(textPair);
//            //mFontColorMap.put(i, color);
//        }

        mPartTextList.add(new PartTextEntity(startIndex, endIndex, color));
        return this;
    }

    private List<PartTextEntity> mPartTextList = new ArrayList<>();


    /**
     * 设置逐渐显示的字符串
     *
     * @param textString
     * @return
     */
    public FadeInTextView setTextString(String textString) {
        if (textString != null) {
            //总字数
            textCount = textString.length();
            //存放单个字的数组
            arr = new String[textCount];
            for (int i = 0; i < textCount; i++) {
                arr[i] = textString.substring(i, i + 1);
            }
            initAnimation();
        }

        return this;
    }

    /**
     * 开启动画
     *
     * @return
     */
    public FadeInTextView startFadeInAnimation() {
        if (textAnimation != null) {
            stringBuffer.setLength(0);
            currentIndex = -1;
            textAnimation.start();
        }
        return this;
    }

    /**
     * 停止动画
     *
     * @return
     */
    public FadeInTextView stopFadeInAnimation() {
        if (textAnimation != null) {
            textAnimation.end();
        }
        return this;
    }

    /**
     * @param duration 每个字出现的时间、
     * @return FadeInTextView实例对象、s
     */
    public FadeInTextView setDuration(long duration) {
        textAnimation.setDuration(textCount * duration);
        return this;
    }

    /**
     * 回调接口
     */
    public interface TextAnimationListener {
        void animationFinish();
    }

    public FadeInTextView setTextAnimationListener(TextAnimationListener textAnimationListener) {
        this.textAnimationListener = textAnimationListener;
        return this;
    }

    public boolean isRunning() {
        return textAnimation != null && textAnimation.isRunning();
    }

}
